import type { PromiseListRes, PromiseRes } from "@/api/response";
import { http } from "@/utils/http";

// ... 接口定义部分保持不变 ...
export interface ClusterInfo {
  id: string;
  name: string;
  server: string;
  version: string;
  status: string;
  source: string;
  environment: string;
}

export interface CreateClusterRequest {
  name: string;
  kubeconfigData: string;
  provider?: string;
  description?: string;
  environment?: string;
  region?: string;
}

export class K8sCluster {
  /** 获取集群列表 */
  getClusterList(): PromiseListRes<ClusterInfo> {
    return http.get("/api/v1/kubeHud/k8s/clusters");
  }

  /** 获取当前活动集群名称 */
  getActiveCluster(): PromiseRes<string> {
    // Go 后端返回 {code: 200, data: "cluster-id", message: "..."} 格式
    return http.get("/api/v1/kubeHud/k8s/clusters/active");
  }

  /** 设置活动集群 */
  setActiveCluster(idOrName: string) {
    // 优先使用 ID，向后兼容 name
    const isId = idOrName.length > 10 && idOrName.includes("-"); // 简单的ID检测
    return http.post("/api/v1/kubeHud/k8s/clusters/active", {
      data: isId ? { id: idOrName } : { name: idOrName }
    });
  }

  /** 创建新集群 */
  createCluster(data: CreateClusterRequest) {
    const payload = {
      ...data,
      kubeconfigData: btoa(data.kubeconfigData)
    };

    return http.post("/api/v1/kubeHud/k8s/clusters", { data: payload });
  }

  /** 删除集群 */
  deleteCluster(clusterId: string) {
    // 现在使用 ID 而不是 name
    return http.delete(`/api/v1/kubeHud/k8s/clusters/${clusterId}`);
  }
}
